package net
{
	import BaseRows.EQrow;
	import BaseRows.SArow;
	
	import data.MyBorderContainer;
	
	import equipments.PU;
	
	import flash.external.ExternalInterface;
	import flash.utils.describeType;
	
	import flashx.textLayout.formats.WhiteSpaceCollapse;
	
	import mx.collections.ArrayCollection;
	import mx.collections.ArrayList;
	import mx.controls.Alert;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.remoting.RemoteObject;
	
	import net.data.Economic;
	import net.data.Figures;
	import net.data.ModelingItem;
	
	import remoteObject.Modeling;
	import remoteObject.Scenario;
	
	import spark.components.BorderContainer;

	public class DoSave
	{
		private var saveItemArr:Array=[];
		
		private var saveFiguresArr:Array=[];
		
		private var saveScenarioArr:Array=[];
		
		private var saveEconomicArr:Array=[];
		
		private var blankStr:String="";
		
		private var saveMo:RemoteObject;
		
		//시나리오모드 remote object
		private var saveSnMo:RemoteObject;
		
		private var saveFmMo:RemoteObject;
		
		private var saveEcMo:RemoteObject; //경제성분석 리모트오브젝트
		
		private var branchIdx:uint;
		private var eqIdx:uint;

		private var saveItem:ModelingItem;
		
		private var currentBRId:String
		private var currentDepth:uint=1;
		
		private var projectID:String;

		public function DoSave(_projectID:String)
		{
			projectID=_projectID;
			
			
			saveMo = new RemoteObject("remoteRO");
			saveSnMo = new RemoteObject("remoteRO");
			saveFmMo = new RemoteObject("remoteRO");
			saveEcMo = new RemoteObject("remoteRO");
			
//			saveMo.addEventListener(FaultEvent.FAULT,ro_fault);
			
//			makeSaveItem()
		}
		
//		protected function ro_fault(event:FaultEvent):void
//		{
//			Alert.show(event.message.toString(),"Error");
//		}
		
		private function ro_result(e:ResultEvent):void
		{
			trace(" ==== remote object 연결 완료 ====")
//			Alert.show(e.result.toString(),"저장 ");
			Alert.show("저장 되었습니다.","알림");
			
		}
		private function ro_FmResult(e:ResultEvent):void
		{
			trace(" ==== remote object 연결 완료 ====")
//				Alert.show(e.result.toString(),"저장 figures");
			
		}
		private function ro_SnResult(e:ResultEvent):void
		{
			trace(" ==== remote object 연결 완료 ====")
//				Alert.show(e.result.toString(),"저장 figures");
			
		}
		
		//전체 item들을 save하기 위해 SaveItem형태의 아이템으로 만드는 메서드
		public function makeSaveItem():void{
			saveItemArr=[];
			saveScenarioArr=[];
			saveFiguresArr=[];
			saveEconomicArr =[];
			
			saveMo.showBusyCursor=true;
			saveMo.addEventListener(ResultEvent.RESULT,ro_result);
			saveSnMo.showBusyCursor=true;
			saveSnMo.addEventListener(ResultEvent.RESULT,ro_SnResult);
			saveFmMo.showBusyCursor=true;
			saveFmMo.addEventListener(ResultEvent.RESULT,ro_FmResult);
			
			trace("====== saveItem ======");
			
			var branchArr:ArrayList = Maros.home.branchArr;
			var branchLen:uint = branchArr.length;
			var branchItem:MyBorderContainer;
			var detailLen:uint;
			var idDate:Date;
			var idDateStr:String;
/*			
			//우선적으로 branch에 uid를 셋팅한다.
			for(branchIdx=0;branchIdx<branchLen;++branchIdx){
				branchItem=Maros.home.branchArr.getItemAt(branchIdx) as MyBorderContainer;
				idDate=new Date();
				idDateStr = idDate.getFullYear()+intToString(idDate.getMonth()+1,2)+intToString(idDate.getDate(),2)+intToString(idDate.getHours(),2)+intToString(idDate.getMinutes(),2)+intToString(idDate.getSeconds(),2)+intToString(idDate.getMilliseconds(),3);
				
				branchItem.itemId = idDateStr;
				trace("branchItem.itemId:",branchItem.itemId);
			}
			*/
			for(branchIdx=0;branchIdx<branchLen;++branchIdx){
				branchItem=Maros.home.branchArr.getItemAt(branchIdx) as MyBorderContainer;
				currentBRId = branchItem.itemId;
				detailLen = branchItem.detailArr.length;
				
				branchToSaveItem(branchArr.getItemAt(branchIdx) as MyBorderContainer);
				
				//브런치에 디테일 아이템이 0보다 클경우 브런치의 디테일을 saveitem으로 만든다
				if(branchItem.detailArr.length>0){
					blankStr="";
					makeEqSaveItem(branchItem);
				}
			}
			
			//setModeling과 setFigures는 자바클래스의 메서드
			saveMo.setModeling(saveItemArr);
			saveSnMo.setScenarioModeling(saveScenarioArr);
			saveFmMo.setFigures(saveFiguresArr);
			if (saveEconomicArr.length > 0)
			{
				saveEcMo.setEconomic(saveEconomicArr);
			}
		}
		
		//branch안에 detailView에 있는 장비의 모델링들을 saveItem으로 만듬
		private function makeEqSaveItem(_bc:MyBorderContainer):void{
//			trace("DoSave.makeEqSaveItem(_bc)");
			
			blankStr+="	";
			var len:uint = _bc.detailArr.length;
			var subItem:MyBorderContainer;
			
			//detailArr의 모든 eq들을 대상으로 루프
			for(var k:uint=0;k<len;++k){
				eqIdx=k;
				subItem = _bc.detailArr.getItemAt(k) as MyBorderContainer
				eqToSaveItem(subItem);
				if (subItem.econo != null)
				{
					saveEconomicArr.push(subItem.econo);
				}
				//eq모델의 detailView에 모델링데이터가 있으면 다시 makeEqSaveItem 한다.
				if(subItem.detailArr.length>0){
					makeEqSaveItem(subItem);
				}
				
				//시나리오뷰 아이템이 있다면 시나리오뷰를 아이템으로 저장
				if(subItem.detailArrForScenario.length>0){
					//시나리오뷰안에 시나리오뷰는 불가함
					//따라서 시나리오뷰는 코루프를 돌 필요가 없음
					saveScenario(subItem);
				}
			}
		}
		
		//branch 를 saveitem으로 저장함
		private function branchToSaveItem(_item:MyBorderContainer):void{
//			trace("DoSave.branchToSaveItem(_item)");
//			ExternalInterface.call("console.log","branchToSaveItem");
			
			var moInStr:String ="";
			var b:MyBorderContainer
			for each(b in _item.pBc){
				moInStr+=b.itemId+"/";
			}
			var moOutStr:String="";
			for each(b in _item.nBc){
				moOutStr+=b.itemId+"/"
			}
			
			saveItem=new ModelingItem();
			saveItem.moProject=projectID;
			saveItem.moBr=_item.itemId; //BR의 아이디 BR000, null
			saveItem.moSelf=_item.itemId; //자기자신의 아이디
			saveItem.moPre=""; //자기 부모의 아이디
			saveItem.moDepth="1"; //자신의 뎁스
			saveItem.moOrder=0;	//자신의 순서(detailView 일때만 순서가 있음)
			saveItem.moType=_item.iName;	//타입
			saveItem.moImg=getImgName( _item.imgUrl.toString());	//아이콘 이미지 
			saveItem.moPosx=_item.x.toString(); //br일때 x좌표
			saveItem.moPosy=_item.y.toString();	//br일때 y좌표
			saveItem.moName=_item.title;	//title네임
			saveItem.moPuEa=0;	//pb일때 pu의 갯수
			saveItem.moPuConnect =1;
			saveItem.moPuName=null;	//pu의 네임
			saveItem.moPuValue=0;	//pu의 값
			saveItem.moPuOrder=0;	//pu의 순서.. 필요없는 듯
			saveItem.moIn=moInStr;	//자신에게 화살표를 보낸 br의 아이디 [br000/br000]
			saveItem.moOut=moOutStr;	//자신이 화살표를 보낸 br의 아이디 [br000/br000]
			
			saveItemArr.push(saveItem);
			
			printSaveItem(saveItem)
		}
		
		private function eqToSaveItem(_item:MyBorderContainer):void{
//			trace("DoSave.eqToSaveItem(_item)");
//			ExternalInterface.call("console.log","eqToSaveItem");
//			ExternalInterface.call("console.log","item.type:"+_item.iName+"  , item.upLevelBc:"+_item.upLeveBc);
			
			saveItem=new ModelingItem();
			saveItem.moProject=projectID;
			saveItem.moBr=currentBRId; //BR의 아이디 BR000, null
			saveItem.moSelf=_item.itemId; //자기자신의 아이디
			
			//eq일때 tagid 셋팅
			if(_item.iName=="eq"){
				saveItem.moTagId = _item.tagId;
				
				//eq의 Figures를 saveFiguresArr에 넣음
				saveEqFigures(_item);
			}
			if(_item.iName =="se"){
				
				//sa의 Figures를 saveFiguresArr에 넣음
				saveSaFigures(_item);
			}
			
			
			_item.itemId=saveItem.moSelf;
			saveItem.moPre=_item.upLeveBc.itemId; //자기 부모의 아이디
			saveItem.moDepth=getDepth(_item).toString(); //자신의 뎁스
			saveItem.moOrder=_item.idx;	//자신의 순서(detailView 일때만 순서가 있음)
			saveItem.moType=_item.iName;	//타입
			ExternalInterface.call("console.log",_item.iName+","+_item.imgUrl); 
			saveItem.moImg=getImgName( _item.imgUrl.toString());	//아이콘 이미지
//			saveItem.moImg= _item.imgUrl.toString();		//아이콘 이미지 
			saveItem.moPosx=_item.x.toString(); //br일때 x좌표
			saveItem.moPosy=_item.y.toString();	//br일때 y좌표
			saveItem.moName=_item.title;	//title네임
			if(_item.iName=="pb"){
				saveItem.moPuEa = _item.pu_num;
				saveItem.moPuName=null;	//pu의 네임
				saveItem.moPuValue=0;	//pu의 값
				saveItem.moPuConnect =1;
			}else if(_item.iName=="pu"){
				saveItem.moPbUid = _item.upLeveBc.itemId;
				saveItem.moPuConnect = PU(_item).parentPB.pu_num;
				saveItem.moPuValue=PU(_item).puPercentage;	//pu의 값
			}else{
				saveItem.moPuEa=0;	//pb일때 pu의 갯수
				saveItem.moPuName=null;	//pu의 네임
				saveItem.moPuConnect =1;
			}
			saveItem.moPuOrder=0;	//pu의 순서.. 필요없는 듯
			saveItem.moIn="";	//자신에게 화살표를 보낸 br의 아이디 [br000/br000]
			saveItem.moOut="";	//자신이 화살표를 보낸 br의 아이디 [br000/br000]
			saveItemArr.push(saveItem);
			
			
			printSaveItem(saveItem) 
		}
		
		
		
		//figures 저장.
		private function saveEqFigures(_item:MyBorderContainer):void{
			
//			saveFiguresArr=[];
			
			var figures:Figures
			for each(var row:EQrow in _item.eqGrid.datas.toArray()){
				figures = new Figures();
				figures.figSubsystem = row.subSystem;
				figures.figMoUid = _item.itemId;
				figures.figTagid = _item.tagId;
				figures.figMoType = _item.iName;
				figures.figMoName = _item.title;
				figures.figFailMode = row.failureMode;
				figures.figFailureTime = Number(row.MTTF);
				figures.figImpFailure = row.impactOfFailure/100;
				figures.figMttr = Number(row.MTTR);
				figures.figImpRepair = row.impactOfRepair/100;
				figures.figProjectUid = parseInt(projectID);
				figures.figDelivery = Number(row.delivery);
				
				figures.figArt = Number(row.MTTR) - Number(row.delivery);
				figures.figRandomNum=0;
//				figures.figRecovFactor=1+(1-Number(row.reliabilityReductionFactor));
				
				//relation
				figures.figEqRef = getEqRelations(row);
				
				figures.figDistribution = getExchangeFailureDistribution(row.distribution);
				figures.figExpMttf = Number(row.MTTF);
				figures.figNormExptMttf = Number(row.expectedValue);
				figures.figNormStdMttf = Number(row.standardDeviation);
				figures.figMinMttf = Number(row.minTTF);
				figures.figMaxMttf = Number(row.maxTTF);
				figures.figMostMttf = Number(row.mostLikelyTTF);
				figures.figWeiCharMttf = Number(row.charactristric);
				figures.figWeiShapeMttf = Number(row.shapeFactor);
				figures.figWeiDeltime = Number(row.timeDelay);
				figures.figImpRecov = Number(row.reliabilityReductionFactor)/100;
				figures.figRepDistribution=getExchangeFailureDistribution(row.repairDistribution);
				trace("row.option_cb_selected:",row.option_cb_selected  ); 
				figures.figRepModRelia=(row.option_cb_selected)?"Y":"N";
				figures.figRepRepeat=(row.infinity_rb_seleced)?"Y":"N";
				figures.figRepUpto=row.upTo;
				
				ExternalInterface.call("console.log",figures);
				
				saveFiguresArr.push(figures);
			}
			
		}
		//figures 저장.
		private function saveSaFigures(_item:MyBorderContainer):void{
			
//			saveFiguresArr=[];
			
			var figures:Figures
			for each(var row:SArow in _item.seGrid.datas.toArray()){
				figures = new Figures();
				figures.figProjectUid = parseInt(projectID);
				figures.figMoUid = _item.itemId;
				figures.figMoType = _item.iName;
				figures.figMoName = _item.title;
				figures.figSeStartDay = row.startData;
				figures.figFreq = row.frequency;
				figures.figFreqUit =  (row.frequencyUnit.substr(0,1)).toUpperCase();
				figures.figCapLoss = row.capLoss/100;
				
				ExternalInterface.call("console.log",figures);
				saveFiguresArr.push(figures);
			}
			
			
		}
		
		//시나리오모델링 저장
		private function saveScenario(_item:MyBorderContainer):void{
			var scenario:Scenario
			
			var len:uint = _item.detailArrForScenario.length;
			var subItem:MyBorderContainer;
			
			//detailArr의 모든 eq들을 대상으로 루프
			for(var k:uint=0;k<len;++k){
				eqIdx=k;
				subItem = _item.detailArrForScenario.getItemAt(k) as MyBorderContainer
			//	trace("1111111111111111111111111111111111111111111 : " + subItem.itemId);
			//}
			
			//for (var i:int=0; i < _item.detailArrForScenario.length; i++)
		//	{
				//var subItem:MyBorderContainer = _item.detailArrForScenario.source[i] as MyBorderContainer;
			//for each(var subItem:MyBorderContainer in _item.detailArrForScenario){
				//var subItem:MyBorderContainer = ar.getItemIndex(0) as MyBorderContainer;
				scenario=new Scenario();
//				scenario.SNMO_UID=subItem.uid;
				scenario.MO_PK=_item.itemId;
				scenario.SNMO_PROJECT=projectID
				scenario.SNMO_BR=this.currentBRId;
				scenario.SNMO_SELF=subItem.itemId
				scenario.SNMO_PRE = _item.itemId;  
				scenario.SNMO_DEPTH = "2";
				scenario.SNMO_ORDER=subItem.idx;
				scenario.SNMO_TYPE=subItem.iName;
				scenario.SNMO_IMG=getImgName( _item.imgUrl.toString());
				scenario.SNMO_POSX = subItem.x;
				scenario.SNMO_POSY = subItem.y;
				scenario.SNMO_NAME=subItem.title;
//				scenario.SNMO__PU_EA
//				scenario.SNMO__PU_NAME
//				scenario.SNMO__PU_VALUE
//				scenario.SNMO__PU_ORDER
//				scenario.SNMO__IN
//				scenario.SNMO__OUT
//				scenario.SNMO__TREE
				scenario.SNMO_TAGID=subItem.tagId;
//				scenario.SNMO_PU_CONNECT
//				scenario.SNMO_PB_UID
				
				saveScenarioArr.push(scenario);
				saveEqFigures(subItem);
			}
		}
		
		
		
		
		/*
			failure distribution을 int로 치환.
		*/
		private function getExchangeFailureDistribution(_str:String):uint{
			switch(_str){
				case "Exponential":
					return 1;
					break;
				case "Normal":
					return 2;
					break;
				case "Rectangular":
					return 3;
					break;
				case "Triangular":
					return 4;
					break;
				case "Weibull(no delay)":
					return 5;
					break;
				case "Weibull(time delay)":
					return 6;
					break;
			}
			return 0;
		}
		
		private function getEqRelations(_row:EQrow):String{
			var rtnStr:String="";
			trace("_row.relationDatas:",_row.relationDatas);
			if(_row.relationDatas==null)return "";
			for each(var _mbc:Object in _row.relationDatas.toArray()){
				trace("_mbc.uid:",_mbc.uid);
				rtnStr+=_mbc.uid+","
			}
			return rtnStr;
		}
		
		
		//imgurl클래스에서..이미지 명만 리턴받기
		private function getImgName(_str:String):String{
			trace(_str);
			
			if(_str=="")return "";
			
			var str:String=_str;
			var rtnStr:String;
			var extArr:Array=["gif","png","jpg"];
			var idx:int;
			var _idx:int;
			
			for each(var ext:String in extArr){
				idx=str.lastIndexOf(ext);
				trace("이미지경로:",idx);
				if(idx!=-1){
					//확장자명 앞의 "_"까지 뒤의 string을 지운
					str = str.substring(0,idx-1);
//					trace("1",str);
					
					//str을 뒤에서부터 "_"를 찾는다.
					_idx=str.lastIndexOf("/");
//					trace("2",_idx);
					
					rtnStr = str.substr(_idx+1);
//					trace("3", rtnStr);
					return rtnStr;
				}
			}
			return "base";
		}
		
		//saveItem의 속성값을 한줄로 나열하여 출력하는 메서드
		private function printSaveItem(_item:ModelingItem):void{
			var rtnStr:String = _item.moSelf;
			
			rtnStr+="\tmoProject:"+_item.moProject;
			rtnStr+="\tmoBr:"+_item.moBr;
			rtnStr+="\tmoSelf:"+_item.moSelf;
			rtnStr+="\tmoTagId:"+_item.moTagId;
			rtnStr+="\tmoPre:"+_item.moPre;
			rtnStr+="\tmoDepth:"+_item.moDepth;
			rtnStr+="\tmoOrder:"+_item.moOrder;
			rtnStr+="\tmoType:"+_item.moType;
			rtnStr+="\tmoImg:"+_item.moImg;
			rtnStr+="\tmoPosx:"+_item.moPosx;
			rtnStr+="\tmoPosy:"+_item.moPosy;
			rtnStr+="\tmoName:"+_item.moName;
			rtnStr+="\tmoPuEa:"+_item.moPuEa;
			rtnStr+="\tmoPbUid:"+_item.moPbUid;
			rtnStr+="\tmoPuConnect:"+_item.moPuConnect;
			rtnStr+="\tmoPuName:"+_item.moPuName;
			rtnStr+="\tmoPuValue:"+_item.moPuValue;
			rtnStr+="\tmoPuOrder:"+_item.moPuOrder;
			rtnStr+="\tmoIn:"+_item.moIn;
			rtnStr+="\tmoOut:"+_item.moOut;
			ExternalInterface.call("console.log",rtnStr);
			trace(rtnStr);
		}
		
		//int를 ?자리 숫자형 string 으로 반환
		private function intToString(
										_n:uint, //string으로 변환할 int값
										_p:uint	//변환할 글자 갯수
									):String{
			var n:String = _n.toString();
			
			//추가할 pre글자수
			var preNum:uint = _p - n.length;
			
			var rtnStr:String="";
			for(var i:uint=0;i<preNum;++i){
				rtnStr+="0";
			}
			rtnStr+=n;
			
			return rtnStr;
		}
		
		//자신의 뎁스를 구하기
		private function getDepth(_item:MyBorderContainer):uint{
			var _depth:uint=1;
			while(_item.upLeveBc!=null){
				_depth++;
				_item = _item.upLeveBc
			}
			return _depth;
		}
		 
		
	}
}